import React, { useEffect, useRef, useState } from 'react'
import { Typography, Steps, Button, Form, Input, Select, message } from 'antd';
import axios from 'axios';
import style from './NewAdd.module.css'
import NewEditor from '../../../components/new-editor/NewEditor';
const { Title } = Typography;

export default function NewAdd(props) {
  const [current, setCurrent] = useState(0)
  const [newCategory, setNewCategory] = useState([])
  const [content, setContent] = useState('')
  const [newForm, setNewForm] = useState('')
  const formRef = useRef(null)

  const user = JSON.parse(localStorage.getItem('token'))
  // 新闻分类
  useEffect(() => {
    axios.get('/categories').then(res => {
      // console.log(res)
      setNewCategory(res.data)
    })
  }, [])

  // 下一步
  const next = () => {
    if (current === 0) {
      // 通过表单验证
      formRef.current.validateFields().then(res => {
        // console.log(res)
        setNewForm(res)
        setCurrent(current + 1)
      }).catch(err => {
        console.log(err)
      })
    } else {
      // 富文本的验证
      if (content === '' || content.trim() === '<p></p>') {
        message.error('请输入值')

      } else {
        setCurrent(current + 1)
      }
    }

  }
  // 上一步
  const prev = () => {
    setCurrent(current - 1)
  }

  // 步骤条信息
  const steps = [
    {
      title: '基本信息',
      description: '新闻标题，新闻分类'
    },
    {
      title: '新闻内容',
      description: '新闻主体内容'
    },
    {
      title: '新闻提交',
      description: '保存草稿或提交审核'
    },
  ]

  // 新闻分类select信息处理函数
  const handleCategory = () => {
    // console.log(newCategory)
    const arr = newCategory.map(item => {
      return {
        value: item.id,
        label: item.title
      }
    })
    return arr
  }

  // 提交至草稿箱或者审核
  const handelRes = (auditState) => {
    // console.log(newForm, content)
    axios.post('/news', {
      "title": newForm.title,
      "categoryId": newForm.categoryId,
      "content": content,
      "region": user.region === '' ? '全球' : user.region,
      "author": user.username,
      "roleId": user.roleId,
      "auditState": auditState,
      "publishState": 0,
      "createTime": Date.now(),
      "star": 0,
      "view": 0,
    }).then(res => {
      message.info(`前往${auditState === 0 ? '草稿箱' : '审核'}中查看你的新闻`)
      props.history.push(auditState === 0 ? '/news-manage/draft' : '/audit-manage/list')
    })
  }

  return (
    <div>
      <Title level={3}>攥写新闻</Title>
      <Steps
        current={current}
        items={steps}
      />


      {/* 第一步 */}
      <div className={current === 0 ? '' : style.hidden}>
        <Form
          ref={formRef}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 600,
            marginTop: 60
          }}
          initialValues={{
            remember: true,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="新闻标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入新闻标题',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="新闻分类"
            name="categoryId"
            rules={[
              {
                required: true,
                message: '请选择新闻分类',
              },
            ]}
          >
            <Select
              // onChange={handleChange}
              options={handleCategory()}
            />
          </Form.Item>
        </Form>

      </div>

      {/* 第二步 */}
      <div className={current === 1 ? '' : style.hidden}>
        <NewEditor getContent={(value) => {
          // console.log(value)
          setContent(value)
        }}></NewEditor>
      </div>

      {/* 第三步 */}
      <div className={current === 2 ? '' : style.hidden}></div>

      {/* 按钮 */}
      <div>
        {current < steps.length - 1 && (<Button type='primary' onClick={() => next()}>下一步</Button>)}
        {current === steps.length - 1 && (
          <span><Button type="primary" onClick={() => handelRes(0)}>
            保存到草稿箱
          </Button>
            <Button type='primary' danger onClick={() => handelRes(1)}>提交审核</Button></span>
        )}
        {current > 0 && (
          <Button
            style={{
              margin: '0 8px',
            }}
            onClick={() => prev()}
          >
            上一步
          </Button>
        )}
      </div>

    </div>
  )
}
